package cz.data.gateway.api.service.impl;

import cz.data.common.utils.SpringContextHolder;
import cz.data.gateway.api.service.IRouteService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

@Service
@Slf4j
public class RouteService implements IRouteService {

    private final Map<String, RouteDefinition> routeDefinitionMaps = new ConcurrentHashMap<>();

    @Override
    public Collection<RouteDefinition> getRouteDefinitions() {
        return routeDefinitionMaps.values();
    }

    @Override
    public boolean save(RouteDefinition routeDefinition) {
        if (Objects.isNull(routeDefinition))
            return false;
        routeDefinitionMaps.put(routeDefinition.getId(), routeDefinition);
        refresh(routeDefinition.getId());
        log.info("新增路由: {}", routeDefinition);
        log.info("新增路由1条,目前路由共{}条", routeDefinitionMaps.size());
        return true;
    }

    @Override
    public boolean delete(String routeId) {
        if (StringUtils.isBlank(routeId)) {
            return false;
        }
        RouteDefinition definition = routeDefinitionMaps.remove(routeId);
        if (Objects.nonNull(definition)) {
            log.info("删除路由: {}", definition);
            log.info("删除路由1条,目前路由共{}条", routeDefinitionMaps.size());
            refresh(routeId);
            return true;
        }
        return false;
    }

    public void refresh(String routeId) {
        if (StringUtils.isNotBlank(routeId)) {
            SpringContextHolder.publishEvent(new RefreshRoutesEvent(routeId));
        }
    }
}
